<?php
/**
 * AdminService
 *
 * @Description 描述
 * @Author look
 * @CreateTime 2022/2/22
 */

namespace app\admin\service;


use app\common\base\ServiceBase;
use app\common\enums\sys\role\DataScope;
use app\common\exception\ApiException;
use app\common\model\AdminModel;
use app\common\model\sys\MenuModel;
use app\common\model\sys\RoleModel;
use app\common\utils\ErrorCode;
use think\model\Collection;

/**
 * admin业务逻辑处理
 */
class AdminService extends ServiceBase {

    public function __construct(
        private AdminModel $adminModel = new AdminModel(),
        private RoleModel $roleModel = new RoleModel(),
        private MenuModel $menuModel = new MenuModel()
    ) {

    }

    /**
     * 密码加密
     * @param string $password
     * @return string
     */
    public function generatePassword(string $password): string {
        return password_hash($password, PASSWORD_BCRYPT);
    }

    /**
     * @param string $password
     * @param string $hash_password
     * @param bool $throw true:抛异常;false:不抛异常,直接访问false
     * @throws ApiException
     */
    public function checkPassword(string $password, string $hash_password, bool $throw = true) :bool|ApiException {
        if (!password_verify($password, $hash_password)) {
            if ($throw) {
                throw new ApiException(...ErrorCode::USER_PASSWORD_ERROR);
            }
            return false;
        }
        return true;
    }

    /**
     * 密码有效性校验规则 必须数字或字母开头,包含数字字母特许符号的8-20位
     * @return string
     */
    public function regexPassword():string {
        return '/^([\da-zA-Z])[\da-zA-Z!#$%^&*,\-\.\@_\+\=\(\)\~\`]{7,19}$/';
    }

    public function getMenusByAdmin(int $admin_id) {
        return $this->getMenusByRoles($this->getRolesByAdmin($admin_id));
    }

    public function getRolesByAdmin(int $admin_id): array|Collection {
        return $this->roleModel->getRolesByAdmin($admin_id) ?? [];
    }

    public function getMenusByRoles($roles) {
        $role_ids = [];
        foreach ($roles as $role) {
            if ($role->data_scope === DataScope::all->value) {
                // 具有全部菜单权限
                return $this->menuModel->select();
            }
            $role_ids[] = $role['id'];
        }

        return $this->menuModel->getMenusByRoles($role_ids);
    }


}